<?php

namespace app\common\service\learn;

use app\common\enums\AccountTypeEnum;
use app\common\enums\AntiForgettingFlagEnum;
use app\common\enums\AppointmentStatusEnum;
use app\common\enums\ClassHourTypeEnum;
use app\common\enums\CourseFullTypeEnum;
use app\common\enums\LearnMeansEnum;
use app\common\enums\LearnSayAntiForgettingStatusEnum;
use app\common\enums\LearnValidStatusEnum;
use app\common\enums\say\StrangeTypeEnum;
use app\common\enums\WordLearnTypeEnum;
use app\common\model\banxi\core\CoreAccountClassHour;
use app\common\model\banxi\core\CoreCourseAppointment;
use app\common\model\banxi\course\Course;
use app\common\model\banxi\Grade;
use app\common\model\banxi\learn\LearnSayAntiForgetting as LearnSayAntiForgettingModel;
use app\common\model\banxi\learn\LearnSayAntiForgettingAnswer;
use app\common\model\banxi\learn\LearnSayAntiForgettingSentence;
use app\common\model\banxi\learn\LearnSayQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSayQuestionRecord;
use app\common\model\banxi\learn\LearnSayReviewRecord;
use app\common\model\banxi\learn\LearnSayReviewSentenceRecord;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\model\banxi\learn\LearnSkRecord as LearnSkRecordModel;
use app\common\model\banxi\learn\LearnSkWordRecord;
use app\common\model\banxi\learn\LearnSubjectQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSubjectQuestionRecord;
use app\common\model\banxi\learn\LearnTwentyAntiForgetting;
use app\common\model\banxi\learn\LearnTwentyAntiForgettingWord;
use app\common\model\banxi\say\SayTeachSentence;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\student\StudentSaySentence;
use app\common\model\banxi\subject\SubjectQuestion;
use app\common\model\banxi\subject\SubjectTeach;
use app\common\model\banxi\subject\SubjectTeachChapter;
use app\common\model\banxi\trainer\Trainer;
use app\common\service\ApiService;
use app\common\service\ConfigService;
use app\common\service\core\CoreAccountClassHourService;
use app\common\service\organization\OrganizationRewardService;
use app\common\service\trainer\TrainerSalaryService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class LearnSkRecordService extends ApiService
{

    /*
     * 抗遗忘周期
     * */
    public function getAntiForgettingDay()
    {
        $days = [1, 2, 3, 5, 7, 9, 12, 14, 17, 21];
        return $days;
    }

    /**
     * 创建21天抗遗忘
     *
     * @param Request $request
     * @param int $trainerId 教练ID
     * @param array $submitData 提交数据
     * @return Response
     */
    public function createTwentyAntiForgetting($trainerId, $submitData)
    {
        // 获取参数
        $appointmentId = isset($submitData['appointmentId']) ? $submitData['appointmentId'] : null;
        $time = isset($submitData['time']) ? $submitData['time'] : null;
        $wordRecordIdList = isset($submitData['wordRecodIdList']) ? $submitData['wordRecodIdList'] : null;

        // 开启事务
        Db::startTrans();
        try {
            // 检查上课记录是否存在
            $LearnSkRecordModel = new LearnSkRecord();
            $learnSkRecord = $LearnSkRecordModel
                ->where('appointmentId', $appointmentId)->find();

            if (!$learnSkRecord) {
                throw new ValidateException('上课记录不存在');
            }

            if ($learnSkRecord['trainerId'] != $trainerId) {
                throw new ValidateException('上课记录不存在');
            }

            $skRecordId = $learnSkRecord['id'];

            // 检查是否已创建过抗遗忘记录
            if ($learnSkRecord['isEnd'] && $learnSkRecord['isCreateAntiForgetting']) {
                throw new ValidateException('上课记录已创建过抗遗忘记录，请不要重复创建');
            }

            // 生成唯一组ID
            $groupId = uniqid();

            // 获取单词记录列表
            $LearnSkWordRecordModel = new LearnSkWordRecord();
            $wordRecordList = [];
            if (!empty($wordRecordIdList)) {
                // 根据指定ID列表获取单词记录
                $wordRecordList = $LearnSkWordRecordModel
                    ->where('skRecordId', $skRecordId)
                    ->where('id', 'in', $wordRecordIdList)
                    ->select()
                    ->toArray();
            } else {
                // 自动读取当前课程所学的单词
                $wordRecordList = $LearnSkWordRecordModel
                    ->where('skRecordId', $skRecordId)
                    ->where('antiForgettingFlag', AntiForgettingFlagEnum::E2) // E2 对应 AntiForgettingFlag.E2
                    ->where('wordLearnType', '<>', WordLearnTypeEnum::E3) // 不等于 WordLearnType.E3
                    ->order('updateTime', 'desc')
                    ->order('id', 'desc')
                    ->select()
                    ->toArray();
            }

            if (empty($wordRecordList)) {
                throw new ValidateException('无可创建的单词记录');
            }

            // 获取课程名称
            $actualCourseIds = explode(',', $learnSkRecord['actualCourseId']);
            $CourseModel = new Course();
            $courseNameList = $CourseModel
                ->where('id', 'in', $actualCourseIds)
                ->column('name');

            if (empty($courseNameList)) {
                throw new ValidateException('实际课程不存在');
            }

            $courseName = implode(',', $courseNameList);

            // 生成21天抗遗忘记录
            $days = [1, 2, 3, 5, 7, 9, 12, 14, 17, 21]; // 21天抗遗忘计划
            $date = date('Y-m-d');
            $twentyAntiForgettingList = [];

            foreach ($days as $day) {
                $futureDate = date('Y-m-d', strtotime("+$day days", strtotime($date)));

                $twentyAntiForgettingList[] = [
                    'title' => $courseName,
                    'groupId' => $groupId,
                    'skRecordId' => $skRecordId,
                    'studentId' => $learnSkRecord['studentId'],
                    'studentOrgId' => $learnSkRecord['studentOrgId'],
                    'trainerAntiForgettingId' => $learnSkRecord['trainerId'],
                    'date' => $futureDate,
                    'time' => $time,
                    'isReview' => 0,
                    'isTeach' => 0,
                    'createTime' => time(),
                    'updateTime' => time(),
                    'del' => 0
                ];
            }

            // 批量保存抗遗忘记录
            $LearnTwentyAntiForgettingModel = new LearnTwentyAntiForgetting();
            $LearnTwentyAntiForgettingModel->insertAll($twentyAntiForgettingList);

            // 更改课程单词抗遗忘记录标识为已创建 (E3)
            $wordRecordIds = array_column($wordRecordList, 'id');
            $LearnSkWordRecordModel
                ->where('id', 'in', $wordRecordIds)
                ->update([
                    'antiForgettingFlag' => AntiForgettingFlagEnum::E3, // E3 对应 AntiForgettingFlag.E3
                    'updateTime' => time()
                ]);

            // 保存抗遗忘单词（按单词去重）
            $twentyAntiForgettingWordList = [];
            $addedWords = []; // 用于去重

            foreach ($wordRecordList as $wordRecord) {
                $word = $wordRecord['word'];
                // 检查单词是否已经添加过
                if (!in_array($word, $addedWords)) {
                    $twentyAntiForgettingWordList[] = [
                        'skRecordId' => $skRecordId,
                        'groupId' => $groupId,
                        'courseId' => $wordRecord['courseId'],
                        'word' => $word,
                        'createTime' => time(),
                        'updateTime' => time(),
                        'del' => 0
                    ];
                    $addedWords[] = $word;
                }
            }

            // 批量保存抗遗忘单词
            if (!empty($twentyAntiForgettingWordList)) {
                $LearnTwentyAntiForgettingWordModel = new LearnTwentyAntiForgettingWord();
                $LearnTwentyAntiForgettingWordModel->insertAll($twentyAntiForgettingWordList);
            }

            // 修改上课记录
            $result = $LearnSkRecordModel
                ->where('id', $skRecordId)
                ->where(function ($query) {
                    $query->where('isCreateAntiForgetting', 0)->whereOr('isEnd', 0);
                })->update([
                    'isCreateAntiForgetting' => 1,
                    'updateTime' => time()
                ]);

            if (!$result) {
                throw new ValidateException('创建失败，请稍后重试');
            }

            // 提交事务
            Db::commit();
            return true;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    //-------------------------------------------------------------------------------------
    //                                   上课                                              -
    //-------------------------------------------------------------------------------------


    /**
     * 开始上课
     *
     * @param int $trainerId 教练ID
     * @param int $appointmentId 预约ID
     */
    public function startSk($trainerId, $appointmentId)
    {
        // 获取排课预约信息
        $CoreCourseAppointmentModel = new CoreCourseAppointment();
        $appointment = $CoreCourseAppointmentModel->where('id', $appointmentId)->find();

        if (empty($appointment)) {
            getResponseException('排课预约不存在', [], 1, 'ERROR');
        }

        if ($appointment['trainerId'] != $trainerId) {
            getResponseException('排课预约不存在', [], 1, 'ERROR');
        }
        $appointmentStatus = $appointment['appointmentStatus'];

        // 如果已经在上课中，直接返回
        if ($appointmentStatus == AppointmentStatusEnum::SK_IN) { // SK_IN
            getResponseException('已经开始上课', [], 1, 'ERROR');
        }

        // 验证预约状态是否为待上课
        if ($appointmentStatus != AppointmentStatusEnum::PENDING_CLASS) { // PENDING_CLASS
            getResponseException('上课失败，排课状态不为待上课', [], 1, 'ERROR');
        }
        // 获取配置的提前开始分钟数
        $ConfigService = new ConfigService();
        $delayStartMinutes = $ConfigService->getSysConfigValue('course_delay_start_minutes');

        if (!empty($delayStartMinutes) && is_numeric($delayStartMinutes)) {
            // 构造预约时间
            $appointmentDateTime = $appointment['date'] . ' ' . $appointment['startTime'];
            $appointmentTime = strtotime($appointmentDateTime);
            $validTime = $appointmentTime - ($delayStartMinutes * 60);
            $currentTime = time();

            if ($validTime > $currentTime) {
                getResponseException("上课时间未到，您可以提前{$delayStartMinutes}分钟开始", [], 1, 'ERROR');
            }
        }

        Db::startTrans();
        try {
            // 更新预约状态为上课中
            $updateResult = $CoreCourseAppointmentModel->update(['appointmentStatus' => AppointmentStatusEnum::SK_IN], [
                'id' => $appointmentId,
                'appointmentStatus' => $appointmentStatus
            ]); // SK_IN

            if (!$updateResult) {
                throw new ValidateException('开始上课失败，请稍后重试', [], 1, 'ERROR');
            }

            // 生成上课记录
            $nowTime = time();
            $studentId = $appointment['studentId'];
            $coreAccountClassHourService = new CoreAccountClassHourService();
            $studentAccount = $coreAccountClassHourService->getByAccountIdAndType($studentId, AccountTypeEnum::STUDENT);
            $coreAccountClassHourModel = new CoreAccountClassHour();
            $classMinutesTotal = $coreAccountClassHourModel->classMinutesTotal(ClassHourTypeEnum::C_60, $studentAccount);
            $studentClassMinute = $coreAccountClassHourModel->classMinutes(ClassHourTypeEnum::C_60, $studentAccount);
            $studentClassMinuteFreeze = $coreAccountClassHourModel->classMinutesFreeze(ClassHourTypeEnum::C_60, $studentAccount);
            $studentClassMinute = $studentClassMinute - $studentClassMinuteFreeze;
            // 构造上课记录数据
            $learnSkRecord = [
                'appointmentId' => $appointmentId,
                'date' => $appointment['date'],
                'actualStartTime' => date('Y-m-d H:i:s', $nowTime),
                'studentId' => $studentId,
                'studentOrgId' => $appointment['studentOrganizationId'],
                'trainerId' => $appointment['trainerId'],
                'courseId' => $appointment['courseId'],
                'courseName' => $appointment['courseName'],
                'courseFullType' => $appointment['courseFullType'],
                'courseDeliveryType' => $appointment['courseDeliveryType'],
                'learnValidStatus' => LearnValidStatusEnum::E1, // E1 有效
                'isEnd' => 0,
                'courseType' => $appointment['courseType'],
                'createTime' => $nowTime,
                'updateTime' => $nowTime,
                'studentClassMinuteTotal' => $classMinutesTotal,
                'studentClassMinute' => $studentClassMinute
            ];

            $courseMinutes = (new CourseFullTypeEnum())->getMinutes($appointment['courseFullType']);
            // 根据课程类型设置结束时间

            $endTime = date('Y-m-d H:i:s', $nowTime + ($courseMinutes * 60));
            $learnSkRecord['endTime'] = $endTime;

            // 插入上课记录
            $LearnSkRecordModel = new LearnSkRecord();
            $recordId = $LearnSkRecordModel->insertGetId($learnSkRecord);
            Db::commit();
        } catch (\Exception|ValidateException $e) {
            Db::rollback();
            //            getResponseException('开始上课失败，请稍后重试', [], 1, 'ERROR');
            getResponseException($e->getMessage(), [], 1, 'ERROR');
        }
        return [
            'recordId' => $recordId,
            'endTime' => $endTime
        ];
    }

    /**
     * 结束上课
     *
     * 计算上课时长，学习统计等
     *
     * @param int $trainerId 教练ID
     * @param int $appointmentId 预约ID
     */
    public function endSk($trainerId, $appointmentId)
    {
        // 开启事务
        Db::startTrans();
        try {
            $CoreCourseAppointmentModel = new CoreCourseAppointment();
            // 获取预约信息
            $appointment = $CoreCourseAppointmentModel->where('id', $appointmentId)->find();
            if (!$appointment) {
                throw new ValidateException('排课预约不存在');
            }

            if ($trainerId != $appointment['trainerId']) {
                throw new ValidateException('排课预约不存在');
            }

            // 获取上课记录
            $LearnSkRecordModel = new LearnSkRecord();
            $learnSkRecord = $LearnSkRecordModel->where('appointmentId', $appointmentId)->find();
            if (!$learnSkRecord) {
                throw new ValidateException('上课记录不存在');
            }

            if ($learnSkRecord['isEnd']) {
                throw new ValidateException('上课已结束');
            }

            $skRecordId = $learnSkRecord['id'];
            $nowTime = date('Y-m-d H:i:s');

            // 计算上课分钟数
            $startTime = strtotime($learnSkRecord['actualStartTime']);
            $endTime = strtotime($nowTime);
            $learnMinutes = bcdiv(bcsub($endTime, $startTime), 60, 2);
            // 更新实体
            $updateSk = [
                'actualEndTime' => $nowTime,
                'isEnd' => 1,
                'learnMinutes' => $learnMinutes
            ];

            // 计算上课的学习情况
            $LearnSkWordRecordModel = new LearnSkWordRecord();
            $wordRecordList = $LearnSkWordRecordModel
                ->where('skRecordId', $skRecordId)
                ->where('wordLearnType', '<>', WordLearnTypeEnum::E3) // WordLearnType.E3
                ->select()
                ->toArray();

            // 复习数量
            $reviewWordNum = 0;
            // 复习遗忘词汇数量
            $reviewForgetWordNum = 0;
            // 学新词汇
            $newWordNum = 0;
            // 学新遗忘词汇
            $newForgetWordNum = 0;
            // 正确数
            $learnCorrectNum = 0;
            // 错误数
            $learnErrorNum = 0;

            foreach ($wordRecordList as $record) {
                // 复习词汇 (WordLearnType.E2)
                if ($record['wordLearnType'] == WordLearnTypeEnum::E2) {
                    $reviewWordNum++;
                    if ($record['isForget']) {
                        $reviewForgetWordNum++;
                    }
                }

                // 新学词汇 (WordLearnType.E1)
                if ($record['wordLearnType'] == 1) {
                    $newWordNum++;
                    if ($record['isForget']) {
                        $newForgetWordNum++;
                    }
                }

                // 正确/错误统计
                if ($record['isForget']) {
                    $learnErrorNum++;
                } else {
                    $learnCorrectNum++;
                }
            }

            // 学习总数
            $learnTotalNum = $newWordNum + $reviewWordNum;

            $updateSk['reviewWordNum'] = $reviewWordNum;
            $updateSk['reviewForgetWordNum'] = $reviewForgetWordNum;
            $updateSk['newWordNum'] = $newWordNum;
            $updateSk['newForgetWordNum'] = $newForgetWordNum;
            $updateSk['learnCorrectNum'] = $learnCorrectNum;
            $updateSk['learnErrorNum'] = $learnErrorNum;
            $updateSk['learnTotalNum'] = $learnTotalNum;

            // 更新上课记录
            $cnt = $LearnSkRecordModel
                ->update($updateSk, ['id' => $skRecordId, 'isEnd' => 0]);

            if (!$cnt) {
                throw new ValidateException('结束上课失败，请稍后重试');
            }

            // 更新预约状态
            $CoreCourseAppointmentModel
                ->update(['appointmentStatus' => AppointmentStatusEnum::END], ['id' => $appointmentId]); // 假设AppointmentStatus.END等于'END'

            //更新授课老师
            $studentId = $learnSkRecord['studentId'];
            $trainerId = $learnSkRecord['trainerId'];
            $studentModel = new Student();
            $studentInfo = $studentModel->where('id', $studentId)->find();
            if ($studentInfo && !$studentInfo['teachTrainerId']) {
                $studentModel->update(['teachTrainerId' => $trainerId], ['id' => $studentId]);
            }

            // 更新阅读理解
            $studentId = $learnSkRecord['studentId'];
            $studentOrgId = $learnSkRecord['studentOrgId'];
            $courseFullType = $learnSkRecord['courseFullType'];
            $courseDeliveryType = $learnSkRecord['courseDeliveryType'];
            $classHourType = (new CourseFullTypeEnum())->getClassHourType($courseFullType); // 需要根据具体业务实现

            if ($classHourType && in_array($classHourType, [1, 2])) {
                // 释放学员冻结课时（扣除学员课时）
                $student = Student::where('id', $studentId)->find();
                // 这里需要根据实际的AccountClassHourCross类实现进行调整
                $accountClassHourCross = new CoreAccountClassHourService();
                $accountClassHourCross->studentReleaseFrozen($student, $classHourType, 1);
                $accountClassHourCross->studentTopClass($student, $classHourType, 1);
            }

            //陪跑奖励
            $organizationRewardService = new OrganizationRewardService();
            $organizationRewardService->companionRunReward($studentId, $appointmentId);

            // 薪资
            $TrainerService = new TrainerSalaryService();
            $messageClass = [
                'trainerId' => $trainerId,
                'project' => $courseFullType, // 需要根据具体业务实现
                'recordId' => $skRecordId,
                'courseDeliveryType' => $courseDeliveryType
            ];
            $TrainerService->handleSalary($messageClass);


            // 提交事务
            Db::commit();
            return true;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    //-------------------------------------------------------------------------------------
    //                                   全科学习                                              -
    //-------------------------------------------------------------------------------------

    /**
     * 开始全科答题
     * @param int|null $skRecordId 上课记录ID
     * @param int|null $studentId 学生ID
     * @param int|null $trainerId 教练ID
     * @param int $learnMeans 学习方式（1-教学，2-练习）
     * @param int $exerciseType 练习类型1课前 2课中 3课后
     * @param int $subjectTeachId 全科课程ID
     * @param int $subjectTeachChapterId 全科课程章节ID
     * @param int $subjectAntiForgettingId 抗遗忘记录ID
     * @return int 阅读记录ID
     * @throws Exception
     */
    public function startSubjectQuestion($skRecordId, $studentId, $trainerId, $learnMeans, $exerciseType, $subjectTeachId, $subjectTeachChapterId, $subjectAntiForgettingId = 0)
    {
        Db::startTrans();
        try {

            $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
            // 如果有上课记录ID，检查是否存在未提交的答题记录
            if ($skRecordId) {
                // 查询是否存在未提交的答题记录
                $lastSubjectQuestionRecordId = $LearnSubjectQuestionRecordModel->where('skRecordId', $skRecordId)
                    ->where('isSubmit', 0)
                    ->order('id', 'asc')
                    ->limit(1)
                    ->value('id');
                // 如果存在未提交的记录，直接返回该记录ID
                if ($lastSubjectQuestionRecordId) {
                    return $lastSubjectQuestionRecordId;
                }
            }

            //初始化课程，章节，习题信息
            $subjectTeach = null;
            $subjectTeachChapter = null;

            //非课后作业需要课程和章节id
            if ($exerciseType != 3) {
                if (!$subjectTeachId || !$subjectTeachChapterId) {
                    throw new ValidateException('请选择课程和章节');
                }
                //课程信息
                $subjectTeachModel = new SubjectTeach();
                $subjectTeach = $subjectTeachModel->where('id', $subjectTeachId)->find();
                //课程章节信息
                $subjectTeachChapterModel = new SubjectTeachChapter();
                $subjectTeachChapter = $subjectTeachChapterModel->where('id', $subjectTeachChapterId)->find();
                if ($exerciseType == 1) {//例题学习(课前)
                    $question_ids_arr = explode(',', $subjectTeachChapter['beforeClassQuestion']);
                } elseif ($exerciseType == 2) {//随堂练习(课中)
                    $question_ids_arr = explode(',', $subjectTeachChapter['inClassQuestion']);
                }
            } else {
                if (!$skRecordId) {
                    throw new ValidateException('请选择上课记录');
                }
                // 查询上课记录
                $learnSkRecord = LearnSkRecord::where('id', $skRecordId)->find();
                $courseAppointment = CoreCourseAppointment::where('id', $learnSkRecord['appointmentId'])->find();
                $subjectTeachModel = new SubjectTeach();
                $subjectTeach = $subjectTeachModel->where('id', $courseAppointment['courseId'])->find();
                //课后作业(课后)
                $question_ids_arr = explode(',', $learnSkRecord['afterClassQuestion']);
            }
            if (!$question_ids_arr) {
                throw new ValidateException('暂无习题');
            }
            //查询相关的习题
            $SubjectQuestionModel = new SubjectQuestion();
            $questionList = $SubjectQuestionModel->where(['status' => 1])->whereIn('id', $question_ids_arr)->select();
            if (!$questionList) {
                throw new ValidateException('暂无习题');
            }
            // 获取学生组织ID
            $studentOrgId = null;
            if ($studentId) {
                $student = Student::where('id', $studentId)->find();

                // 验证学生是否存在
                if (empty($student)) {
                    throw new Exception('学员不存在');
                }

                $studentOrgId = $student['organizationId'];
            }


            // 创建答题记录
            $LearnSubjectQuestionData = [
                'skRecordId' => $skRecordId,
                'subjectTeachId' => $subjectTeachId,
                'subjectTeachName' => $subjectTeach ? $subjectTeach['name'] : '',
                'subjectTeachChapterId' => $subjectTeachChapterId,
                'subjectTeachChapterName' => $subjectTeachChapter ? $subjectTeachChapter['name'] : '',
                'studentId' => $studentId,
                'studentOrgId' => $studentOrgId,
                'trainerId' => $trainerId,
                'exerciseType' => $exerciseType,
                'passRate' => 60,
                'answerStartTime' => date('Y-m-d H:i:s'),
                'learnMeans' => $learnMeans,  // 1-教学，2-练习，3-抗遗忘
                'subjectAntiForgettingId' => $subjectAntiForgettingId,
                'createTime' => time(),
                'updateTime' => time()
            ];
            $record = $LearnSubjectQuestionRecordModel->create($LearnSubjectQuestionData);

            // 保存题目信息
            $learnSubjectQuestionAnswerDataList = [];
            foreach ($questionList as $question) {
                $learnSubjectQuestionAnswerDataList[] = [
                    'recordId' => $record->id,
                    'studentId' => $studentId,
                    'trainerId' => $trainerId,
                    'courseId' => $subjectTeach['id'],
                    'questionId' => $question['id'],
                    'questionName' => $question['name'],
                    'titlePicture' => $question['titlePicture'],
                    'questionType' => $question['questionType'],
                    'option' => $question['option'],
                    'answer' => $question['answer'],
                    'analysis' => $question['analysis']
                    //                    'createTime' => time(),
                    //                    'updateTime' => time()
                ];
            }
            // 批量保存题目信息
            $LearnSubjectQuestionAnswerRecordModel = new LearnSubjectQuestionAnswerRecord();
            $LearnSubjectQuestionAnswerRecordModel->saveAll($learnSubjectQuestionAnswerDataList);

            Db::commit();
            return $record->id;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 提交全科答题
     * @param int $skRecordId 上课ID
     * @param int|null $trainerId 教练ID
     * @param int|null $studentId 学生ID
     * @param array|null $answerList 答案列表
     * @throws Exception
     */
    public function answerSubjectQuestion($recordId, $trainerId, $studentId, $answerList)
    {
        Db::startTrans();
        try {

            $LearnSkRecordModel = new LearnSkRecord();
            //查询答题记录
            $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
            $learnSubjectQuestionRecord = $LearnSubjectQuestionRecordModel
                ->where('id', $recordId)
                ->find();
            if (!$learnSubjectQuestionRecord) {
                throw new ValidateException('答题记录不存在');
            }
            if ($learnSubjectQuestionRecord['isSubmit'] == 1) {
                throw new ValidateException('请勿重复提交');
            }
            // 如果提供了教练ID，验证教练权限
            if ($trainerId) {
                if ($learnSubjectQuestionRecord['trainerId'] != $trainerId) {
                    throw new ValidateException('答题记录不存在');
                }
            }

            // 如果提供了学生ID，验证学生权限
            if ($studentId) {
                if ($learnSubjectQuestionRecord['studentId'] != $studentId) {
                    throw new ValidateException('答题记录不存在');
                }
            }

            $skRecordId = $learnSubjectQuestionRecord['skRecordId'];
            if ($skRecordId) {
                // 查询上课记录
                $learnSkRecord = $LearnSkRecordModel->where('id', $skRecordId)->find();

                // 验证上课记录是否存在
                if (empty($learnSkRecord)) {
                    throw new ValidateException('上课记录不存在');
                }
            }
            $LearnSubjectQuestionAnswerRecordModel = new LearnSubjectQuestionAnswerRecord();
            $learnSubjectQuestionAnswerRecordList = $LearnSubjectQuestionAnswerRecordModel
                ->where('recordId', $recordId)
                ->select();
            // 验证题目是否存在
            if (empty($learnSubjectQuestionAnswerRecordList)) {
                throw new ValidateException('提交失败，当前课程无题目');
            }

            //            halt($answerList);
            $updateLearnSubjectAnswerList = [];

            // 处理每个题目答案
            foreach ($learnSubjectQuestionAnswerRecordList as $it) {
                $result = null;

                // 在用户答案中查找对应题目的答案
                if (!empty($answerList)) {
                    foreach ($answerList as $answer) {
                        if (isset($answer['id']) && $answer['id'] == $it['questionId']) {
                            $result = $answer;
                            break;
                        }
                    }
                }

                $LearnSubjectQuestionAnswerRecordModel = new LearnSubjectQuestionAnswerRecord();
                // 判断题目是否正确
                $isCorrect = false;
                $userAnswerList = [];
                $answerRecordId = 0;
                if ($result !== null) {
                    $questionType = $it['questionType'];
                    $userAnswerList = isset($result['userAnswerList']) ? $result['userAnswerList'] : [];
                    $userAnswerImage = isset($result['userAnswerImage']) ? $result['userAnswerImage'] : '';
                    //获取答题记录ID
                    $answerRecord = $LearnSubjectQuestionAnswerRecordModel->where(['questionId' => $result['id'], 'recordId' => $recordId])->find();
                    $answerRecordId = $answerRecord['id'];
                    // 移除空字符串
                    $userAnswerList = array_filter($userAnswerList, function ($value) {
                        return trim($value) !== '';
                    });

                    // 根据题目类型判断答案是否正确
                    switch ($questionType) {
                        case 1: // 1 对应 QuestionType.E1 单选
                            $answerListArray = json_decode($it['answer'], true);
                            if (!is_array($answerListArray)) {
                                $answerListArray = [$it['answer']];
                            }

                            $isCorrect = count($userAnswerList) == 1 && in_array($userAnswerList[0], $answerListArray);
                            break;

                        case 2: // 2 对应 QuestionType.E2 多选
                            if (!empty($userAnswerList)) {
                                $answerListArray = json_decode($it['answer'], true);
                                if (!is_array($answerListArray)) {
                                    $answerListArray = [$it['answer']];
                                }

                                // 检查用户答案是否包含所有正确答案
                                $isCorrect = !empty(array_diff($answerListArray, $userAnswerList)) === false
                                    && !empty(array_diff($userAnswerList, $answerListArray)) === false;
                            }
                            break;
                        case 3: // 简答默认算错老师批改
                            $isCorrect = false;
                            break;
                    }
                }

                // 构造更新数据
                $updateLearnSubjectAnswerList[] = [
                    'answerRecordId' => $answerRecordId,
                    'questionId' => $it['questionId'],
                    'isCorrect' => $isCorrect,
                    'userAnswer' => json_encode($userAnswerList, JSON_UNESCAPED_UNICODE),
                    'userAnswerImage' => $userAnswerImage
                ];
            }
            //            halt($updateLearnSubjectAnswerList);
            // 更新统计信息
            $totalNum = count($updateLearnSubjectAnswerList);
            $correctNum = 0;

            // 统计正确题目数量
            foreach ($updateLearnSubjectAnswerList as $answer) {
                if ($answer['isCorrect']) {
                    $correctNum++;
                }
            }

            $errorNum = $totalNum - $correctNum;
            $correctRate = $totalNum > 0 ? intval($correctNum * 100 / $totalNum) : 0;

            // 构造更新数据
            $endTimeStamp = time();
            $useTime = $endTimeStamp - strtotime($learnSubjectQuestionRecord['answerStartTime']);
            $updateLearnSubjectRecordData = [
                'totalNum' => $totalNum,
                'rightNum' => $correctNum,
                'errorNum' => $errorNum,
                'rightRate' => $correctRate,
                'answerEndTime' => date('Y-m-d H:i:s', $endTimeStamp),
                'useTime' => $useTime,
                'isSubmit' => 1,
                'updateTime' => time()
            ];

            // 更新答题记录
            $cnt = $LearnSubjectQuestionRecordModel
                ->update($updateLearnSubjectRecordData, ['id' => $recordId]);

            // 更新答题答案

            foreach ($updateLearnSubjectAnswerList as $answer) {
                $LearnSubjectQuestionAnswerRecordModel
                    ->update([
                        'isCorrect' => $answer['isCorrect'],
                        'userAnswer' => $answer['userAnswer'],
                        'userAnswerImage' => $answer['userAnswerImage'],
                        'updateTime' => time()
                    ], ['id' => $answer['answerRecordId']]);
            }
            Db::commit();
            return true;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 批改全科答题
     * @param int $skRecordId 上课ID
     * @param int|null $trainerId 教练ID
     * @param int|null $studentId 学生ID
     * @param array|null $answerList 答案列表
     * @throws Exception
     */
    public function correctSubjectQuestion($recordId, $trainerId, $studentId, $answerList)
    {
        Db::startTrans();
        try {

            $LearnSkRecordModel = new LearnSkRecord();
            //查询答题记录
            $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
            $learnSubjectQuestionRecord = $LearnSubjectQuestionRecordModel
                ->where('id', $recordId)
                ->find();
            if (!$learnSubjectQuestionRecord) {
                throw new ValidateException('答题记录不存在');
            }
            // 如果提供了教练ID，验证教练权限
            if ($trainerId) {
                if ($learnSubjectQuestionRecord['trainerId'] != $trainerId) {
                    throw new ValidateException('答题记录不存在');
                }
            }

            // 如果提供了学生ID，验证学生权限
            if ($studentId) {
                if ($learnSubjectQuestionRecord['studentId'] != $studentId) {
                    throw new ValidateException('答题记录不存在');
                }
            }

            $skRecordId = $learnSubjectQuestionRecord['skRecordId'];
            if ($skRecordId) {
                // 查询上课记录
                $learnSkRecord = $LearnSkRecordModel->where('id', $skRecordId)->find();

                // 验证上课记录是否存在
                if (empty($learnSkRecord)) {
                    throw new ValidateException('上课记录不存在');
                }
            }

            //            halt($answerList);
            $LearnSubjectQuestionAnswerRecordModel = new LearnSubjectQuestionAnswerRecord();

            // 更新答题结果
            foreach ($answerList as $answer) {
                $LearnSubjectQuestionAnswerRecordModel->update(['isCorrect' => $answer['isCorrect']], ['id' => $answer['id']]);
            }

            // 更新统计信息
            $totalNum = count($answerList);
            $correctNum = 0;

            // 统计正确题目数量
            foreach ($answerList as $answer) {
                if ($answer['isCorrect']) {
                    $correctNum++;
                }
            }

            $errorNum = $totalNum - $correctNum;
            $correctRate = $totalNum > 0 ? intval($correctNum * 100 / $totalNum) : 0;

            // 构造更新数据
            $updateLearnSubjectRecordData = [
                'totalNum' => $totalNum,
                'rightNum' => $correctNum,
                'errorNum' => $errorNum,
                'rightRate' => $correctRate,
                'updateTime' => time()
            ];

            // 更新答题记录
            $cnt = $LearnSubjectQuestionRecordModel
                ->update($updateLearnSubjectRecordData, ['id' => $recordId]);
            Db::commit();
            return true;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }



    //-------------------------------------------------------------------------------------
    //                                   句型学习                                              -
    //-------------------------------------------------------------------------------------

    /**
     * 开始句型答题
     * @param int|null $skRecordId 上课记录ID
     * @param int|null $studentId 学生ID
     * @param int|null $trainerId 教练ID
     * @param int $learnMeans 学习方式（1-教学，2-练习）
     * @param int $teachSentenceId 句型母句id
     * @return int 阅读记录ID
     * @throws Exception
     */
    public function startSayQuestion($skRecordId, $studentId, $trainerId, $learnMeans, $teachSentenceId)
    {
        Db::startTrans();
        try {
            // 检查是否存在未提交的答题记录
            $existingRecordId = $this->checkExistingUnsubmittedRecord($skRecordId, $teachSentenceId);
            if ($existingRecordId) {
                Db::commit();
                return $existingRecordId;
            }

            // 验证参数并获取基础数据
            $validationData = $this->validateAndPrepareData($studentId, $teachSentenceId);

            // 获取子句型数据并计算总数
            $childTeachSentence = SayTeachSentence::where('parentId', $teachSentenceId)->select();
            $totalNum = count($childTeachSentence) + 1;

            // 创建答题记录
            $record = $this->createQuestionRecord(
                $skRecordId,
                $studentId,
                $trainerId,
                $learnMeans,
                $teachSentenceId,
                $validationData['teachSentence']['name'],
                $validationData['studentOrgId'],
                $totalNum
            );

            // 准备并保存题目信息
            $questionAnswerDataList = $this->prepareQuestionAnswerData(
                $record->id,
                $studentId,
                $trainerId,
                $validationData['teachSentence'],
                $childTeachSentence
            );

            $this->saveQuestionAnswerData($questionAnswerDataList);

            Db::commit();
            return $record->id;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 检查是否存在未提交的答题记录
     */
    private function checkExistingUnsubmittedRecord($skRecordId, $teachSentenceId)
    {
        if (!$skRecordId) {
            return false;
        }
        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        return $learnSayQuestionRecordModel->where([
            'skRecordId' => $skRecordId,
            'sayTeachSentenceId' => $teachSentenceId,
            'isSubmit' => 0
        ])
            ->order('id', 'asc')
            ->limit(1)
            ->value('id');
    }

    /**
     * 验证参数并准备基础数据
     */
    private function validateAndPrepareData($studentId, $teachSentenceId)
    {
        // 获取学生组织ID
        $studentOrgId = null;
        if ($studentId) {
            $student = Student::where('id', $studentId)->find();
            if (empty($student)) {
                throw new ValidateException('学员不存在');
            }
            $studentOrgId = $student['organizationId'];
        }

        // 验证句型ID
        if (!$teachSentenceId) {
            throw new ValidateException('请选择课程');
        }

        // 获取句型数据
        $teachSentence = SayTeachSentence::where('id', $teachSentenceId)->find();
        if (empty($teachSentence)) {
            throw new ValidateException('句型不存在');
        }

        return [
            'studentOrgId' => $studentOrgId,
            'teachSentence' => $teachSentence
        ];
    }

    /**
     * 创建答题记录
     */
    private function createQuestionRecord($skRecordId, $studentId, $trainerId, $learnMeans, $teachSentenceId, $teachSentenceName, $studentOrgId, $totalNum)
    {
        $learnSayQuestionData = [
            'skRecordId' => $skRecordId,
            'sayTeachSentenceId' => $teachSentenceId,
            'sayTeachSentenceName' => $teachSentenceName,
            'studentId' => $studentId,
            'studentOrgId' => $studentOrgId,
            'trainerId' => $trainerId,
            'totalNum' => $totalNum,
            'passRate' => 60,
            'answerStartTime' => date('Y-m-d H:i:s'),
            'learnMeans' => $learnMeans, // 1-教学，2-练习
            'createTime' => time(),
            'updateTime' => time()
        ];

        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        return $learnSayQuestionRecordModel->create($learnSayQuestionData);
    }

    /**
     * 准备题目答案数据
     */
    private function prepareQuestionAnswerData($recordId, $studentId, $trainerId, $teachSentence, $childTeachSentence)
    {
        $baseData = [
            'recordId' => $recordId,
            'studentId' => $studentId,
            'trainerId' => $trainerId,
            'isCorrect' => '-1',
            'listenScore' => '0',
            'listenCorrect' => '-1',
            'translationCorrect' => '-1',
            'answerCorrect' => '-1',
            'createTime' => time(),
            'updateTime' => time()
        ];

        $questionAnswerDataList = [];

        // 添加母句数据（母句的parentTeachSentenceId为0）
        $questionAnswerDataList[] = array_merge($baseData, [
            'parentTeachSentenceId' => 0,
            'sayTeachSentenceId' => $teachSentence['id'],
            'sayTeachSentenceName' => $teachSentence['name'],
            'sentenceEn' => $teachSentence['sentenceEn'],
            'sentenceZh' => $teachSentence['sentenceZh'],
            'sentencePhonetic' => $teachSentence['sentencePhonetic'],
            'sentenceAudio' => $teachSentence['sentenceAudio'],
            'sentenceImage' => $teachSentence['sentenceImage'],
            'sentenceWordColor' => $teachSentence['sentenceWordColor'],
            'splitSentence' => $teachSentence['splitSentence'],
            'intonationGroup' => $teachSentence['intonationGroup'],
            'coreVocabulary' => $teachSentence['coreVocabulary'],
            'expandVocabulary' => $teachSentence['expandVocabulary'],
            'question' => $teachSentence['question'],
            'answer' => $teachSentence['answer']
        ]);

        // 添加子句数据
        foreach ($childTeachSentence as $sentence) {
            $questionAnswerDataList[] = array_merge($baseData, [
                'parentTeachSentenceId' => $sentence['parentId'],
                'sayTeachSentenceId' => $sentence['id'],
                'sayTeachSentenceName' => $sentence['name'],
                'sentenceEn' => $sentence['sentenceEn'],
                'sentenceZh' => $sentence['sentenceZh'],
                'sentencePhonetic' => $sentence['sentencePhonetic'],
                'sentenceAudio' => $sentence['sentenceAudio'],
                'sentenceImage' => $sentence['sentenceImage'],
                'sentenceWordColor' => $sentence['sentenceWordColor']
            ]);
        }

        return $questionAnswerDataList;
    }

    /**
     * 保存题目答案数据
     */
    private function saveQuestionAnswerData($questionAnswerDataList)
    {
        $learnSayQuestionAnswerRecordModel = new LearnSayQuestionAnswerRecord();
        $learnSayQuestionAnswerRecordModel->saveAll($questionAnswerDataList);
    }


    /**
     * 提交句型答题
     * @param int $recordId 答题记录ID
     * @param int|null $trainerId 教练ID
     * @param int|null $studentId 学生ID
     * @param array|null $answerList 答案列表
     * @return int|false
     * @throws Exception
     */
    public function answerSayQuestion($recordId, $trainerId, $studentId, $answerList)
    {
        Db::startTrans();
        try {
            // 验证答题记录
            $learnSayQuestionRecord = $this->validateQuestionRecord($recordId, $trainerId, $studentId);

            // 获取上课记录信息
            $skRecordId = $learnSayQuestionRecord['skRecordId'];
            [$strangeType, $actualStudentId] = $this->getStudentInfo($skRecordId, $studentId);

            // 处理答题答案
            $processResult = $this->processAnswers($recordId, $answerList, $actualStudentId, $strangeType);

            // 更新统计信息
            $this->updateStatistics($recordId, $actualStudentId, $strangeType, $learnSayQuestionRecord, $processResult);

            // 保存生词本
            if (!empty($processResult['studentSaySentence'])) {
                $studentSaySentenceModel = new StudentSaySentence();
                $studentSaySentenceModel->saveStudentSentence($processResult['studentSaySentence']);
            }
            Db::commit();
            return $recordId;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 验证答题记录
     */
    private function validateQuestionRecord($recordId, $trainerId, $studentId)
    {
        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        $learnSayQuestionRecord = $learnSayQuestionRecordModel->where('id', $recordId)->find();

        if (!$learnSayQuestionRecord) {
            throw new ValidateException('答题记录不存在');
        }

        if ($learnSayQuestionRecord['isSubmit'] == 1) {
            throw new ValidateException('请勿重复提交');
        }

        // 验证教练权限
        if ($trainerId && $learnSayQuestionRecord['trainerId'] != $trainerId) {
            throw new ValidateException('答题记录不存在');
        }

        // 验证学生权限
        if ($studentId && $learnSayQuestionRecord['studentId'] != $studentId) {
            throw new ValidateException('答题记录不存在');
        }

        return $learnSayQuestionRecord;
    }

    /**
     * 获取学生信息
     */
    private function getStudentInfo($skRecordId, $studentId)
    {
        $strangeType = StrangeTypeEnum::E2;
        $actualStudentId = $studentId;

        if ($skRecordId) {
            $learnSkRecord = LearnSkRecord::where('id', $skRecordId)->find();
            if (empty($learnSkRecord)) {
                throw new ValidateException('上课记录不存在');
            }
            $strangeType = StrangeTypeEnum::E1;
            $actualStudentId = $learnSkRecord['studentId'];
        }

        return [$strangeType, $actualStudentId];
    }

    /**
     * 处理答题答案
     */
    private function processAnswers($recordId, $answerList, $studentId, $strangeType)
    {
        $learnSayQuestionAnswerRecordModel = new LearnSayQuestionAnswerRecord();
        $learnSayQuestionAnswerRecordList = $learnSayQuestionAnswerRecordModel
            ->where('recordId', $recordId)
            ->select();

        if (empty($learnSayQuestionAnswerRecordList)) {
            throw new ValidateException('提交失败，当前课程无题目');
        }

        $result = [
            'updateLearnSayAnswerList' => [],
            'studentSaySentence' => [],
            'sayTeachSentenceIds' => [],
            'learnNum' => 0,
            'listenLearnNum' => 0,
            'translationLearnNum' => 0,
            'answerLearnNum' => 0
        ];
        foreach ($learnSayQuestionAnswerRecordList as $it) {
            $answer = $this->findAnswerById($answerList, $it['sayTeachSentenceId']);

            if ($answer !== null) {
                $processAnswerResult = $this->processSingleAnswer(
                    $it,
                    $answer,
                    $recordId,
                    $studentId,
                    $strangeType,
                    $learnSayQuestionAnswerRecordModel
                );

                if ($processAnswerResult['isCorrect'] != -1) {
                    $result['updateLearnSayAnswerList'][] = $processAnswerResult['updateData'];
                    if (!in_array($it['sayTeachSentenceId'], $result['sayTeachSentenceIds'])) {
                        $result['sayTeachSentenceIds'][] = $it['sayTeachSentenceId'];
                    }
                    $result['learnNum']++;
                    if ($strangeType == StrangeTypeEnum::E2 && $studentId) {
                        // 学生自学
                        $result['listenLearnNum']++;
                    } else {
                        // 教学+教练自学
                        $result['translationLearnNum']++;
                        $result['answerLearnNum']++;
                    }

                    if (!empty($processAnswerResult['studentSaySentence'])) {
                        $result['studentSaySentence'][] = $processAnswerResult['studentSaySentence'];
                    }
                }
            }
        }

        return $result;
    }

    /**
     * 处理单个答案
     */
    private function processSingleAnswer($questionRecord, $answer, $recordId, $studentId, $strangeType, $model)
    {
        $answerRecord = $model->where([
            'sayTeachSentenceId' => $answer['id'],
            'recordId' => $recordId
        ])->find();

        $answerRecordId = $answerRecord['id'];

        // 根据不同学习场景处理答案正确性判断
        if ($strangeType == StrangeTypeEnum::E2 && $studentId) {
            // 学生自学模式
            $translationCorrect = -1;
            $answerCorrect = -1;
            $listenCorrect = (int)($answer['listenCorrect'] ?? 0);
            $listenScore = (int)($answer['listenScore'] ?? 0);
            $isCorrect = $listenCorrect;
        } else {
            // 教学模式+教练自学模式
            $listenCorrect = 0;
            $listenScore = 0;
            $translationCorrect = (int)($answer['translationCorrect'] ?? 0);
            $answerCorrect = (int)($answer['answerCorrect'] ?? 0);
            $isCorrect = (int)($translationCorrect && $answerCorrect);
        }


        $studentSaySentence = null;
        if ($studentId && $isCorrect == 0) {
            $studentSaySentence = [
                'studentId' => $studentId,
                'sayTeachSentenceId' => $questionRecord['sayTeachSentenceId'],
                'strangeType' => $strangeType,
                'sentenceEn' => $questionRecord['sentenceEn'],
                'sentenceZh' => $questionRecord['sentenceZh'],
                'sentencePhonetic' => $questionRecord['sentencePhonetic'],
                'sentenceAudio' => $questionRecord['sentenceAudio'],
                'sentenceImage' => $questionRecord['sentenceImage'],
                'sentenceWordColor' => $questionRecord['sentenceWordColor'],
                'isCorrect' => $isCorrect
            ];
        }

        return [
            'isCorrect' => $isCorrect,
            'updateData' => [
                'answerRecordId' => $answerRecordId,
                'isCorrect' => $isCorrect,
                'listenScore' => $listenScore,
                'listenCorrect' => $listenCorrect,
                'translationCorrect' => $translationCorrect,
                'answerCorrect' => $answerCorrect,
            ],
            'studentSaySentence' => $studentSaySentence
        ];
    }

    /**
     * 更新统计信息
     */
    private function updateStatistics($recordId, $studentId, $strangeType, $learnSayQuestionRecord, $processResult)
    {
        $learnNum = $processResult['learnNum'];
        $updateLearnSayAnswerList = $processResult['updateLearnSayAnswerList'];
        $listenLearnNum = $processResult['listenLearnNum'];
        $translationLearnNum = $processResult['translationLearnNum'];
        $answerLearnNum = $processResult['answerLearnNum'];

        // 统计正确数量
        $correctNum = 0;
        $listenCorrectNum = 0;
        $translationCorrectNum = 0;
        $answerCorrectNum = 0;

        if ($strangeType == StrangeTypeEnum::E2 && $studentId) {
            // 学生自学
            foreach ($updateLearnSayAnswerList as $answer) {
                if ($answer['isCorrect']) {
                    $correctNum++;
                }
                if ($answer['listenCorrect']) {
                    $listenCorrectNum++;
                }
            }

            // 计算总体错误数和正确率
            $errorNum = $learnNum - $correctNum;
            $correctRate = $learnNum > 0 ? intval($errorNum * 100 / $learnNum) : 0;
            //听力
            $listenErrorNum = $listenLearnNum - $listenCorrectNum;
            $listenCorrectRate = $listenLearnNum > 0 ? intval($listenErrorNum * 100 / $listenLearnNum) : 0;

            // 其他指标保持默认值0
            $translationErrorNum = 0;
            $translationCorrectRate = 0;
            $answerErrorNum = 0;
            $answerCorrectRate = 0;
        } else {
            // 教学和教练自学模式，统计各项正确数
            foreach ($updateLearnSayAnswerList as $answer) {
                if ($answer['isCorrect']) {
                    $correctNum++;
                }
                if ($answer['translationCorrect']) {
                    $translationCorrectNum++;
                }
                if ($answer['answerCorrect']) {
                    $answerCorrectNum++;
                }
            }

            // 计算各项错误数和正确率
            $errorNum = $learnNum - $correctNum;
            $correctRate = $learnNum > 0 ? intval($errorNum * 100 / $learnNum) : 0;

            $translationErrorNum = $translationLearnNum - $translationCorrectNum;
            $translationCorrectRate = $translationLearnNum > 0 ? intval($translationErrorNum * 100 / $translationLearnNum) : 0;

            $answerErrorNum = $answerLearnNum - $answerCorrectNum;
            $answerCorrectRate = $answerLearnNum > 0 ? intval($answerErrorNum * 100 / $answerLearnNum) : 0;

            $listenErrorNum = 0;
            $listenCorrectRate = 0;
        }

        // 计算新学单词/句子数
        $learnSentenceCount = 0;
        $learnWordCount = 0;

        if (!empty($processResult['sayTeachSentenceIds'])) {
            $sayTeachSentenceModel = new SayTeachSentence();
            $sayTeachSentenceList = $sayTeachSentenceModel
                ->whereIn('id', $processResult['sayTeachSentenceIds'])
                ->column('coreVocabulary');

            $coreVocabularyList = [];
            foreach ($sayTeachSentenceList as $item) {
                $coreVocabulary = $item ? json_decode($item, true) : [];
                foreach ($coreVocabulary as $value) {
                    if (!in_array($value['wordEn'], $coreVocabularyList)) {
                        $coreVocabularyList[] = $value['wordEn'];
                    }
                }
                $learnSentenceCount++;
            }
            $learnWordCount = count($coreVocabularyList);
        }

        // 更新答题记录
        $endTimeStamp = time();
        $useTime = $endTimeStamp - strtotime($learnSayQuestionRecord['answerStartTime']);
        $answerDuration = bcdiv($useTime, 60, 2);

        $updateLearnSayRecordData = [
            //整体统计
            'learnNum' => $learnNum,
            'rightNum' => $correctNum,
            'errorNum' => $errorNum,
            'rightRate' => $correctRate,
            // 听力统计
            'listenLearnNum' => $listenLearnNum,
            'listenRightNum' => $listenCorrectNum,
            'listenErrorNum' => $listenErrorNum,
            'listenRightRate' => $listenCorrectRate,
            // 汉译英统计
            'translationLearnNum' => $translationLearnNum,
            'translationRightNum' => $translationCorrectNum,
            'translationErrorNum' => $translationErrorNum,
            'translationRightRate' => $translationCorrectRate,
            // 考点复现统计
            'answerLearnNum' => $answerLearnNum,
            'answerRightNum' => $answerCorrectNum,
            'answerErrorNum' => $answerErrorNum,
            'answerRightRate' => $answerCorrectRate,
            'answerEndTime' => date('Y-m-d H:i:s', $endTimeStamp),
            'useTime' => $useTime,
            'answerDuration' => $answerDuration,
            'learnSentenceCount' => $learnSentenceCount,
            'learnWordCount' => $learnWordCount,
            'isSubmit' => 1,
            'updateTime' => time()
        ];

        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        $learnSayQuestionRecordModel->update($updateLearnSayRecordData, ['id' => $recordId]);

        // 更新答题答案
        $learnSayQuestionAnswerRecordModel = new LearnSayQuestionAnswerRecord();
        foreach ($updateLearnSayAnswerList as $answer) {
            $learnSayQuestionAnswerRecordModel->update([
                'isCorrect' => $answer['isCorrect'],
                'listenScore' => $answer['listenScore'],
                'listenCorrect' => $answer['listenCorrect'],
                'translationCorrect' => $answer['translationCorrect'],
                'answerCorrect' => $answer['answerCorrect'],
                'updateTime' => time()
            ], ['id' => $answer['answerRecordId']]);
        }
    }

    /**
     * 根据ID查找答案
     */
    private function findAnswerById($answerList, $id)
    {
        if (empty($answerList)) {
            return null;
        }

        foreach ($answerList as $answer) {
            if (isset($answer['id']) && $answer['id'] == $id) {
                return $answer;
            }
        }

        return null;
    }


    //学习报告
    public function questionReport($questionRecordId)
    {
        // 获取学习记录及关联信息
        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        $questionRecord = $learnSayQuestionRecordModel->with([
            'student' => function ($query) {
                $query->field('id,name,avatar,gradeId');
            },
            'trainer' => function ($query) {
                $query->field('id,name,avatar');
            }
        ])->where([
            'id' => $questionRecordId,
            'isSubmit' => 1
        ])->find();

        if (empty($questionRecord)) {
            getResponseException('学习记录不存在', [], 1, 'ERROR');
        }

        // 获取学生年级信息
        $questionRecord['student']['gradeInfo'] = null;
        if ($questionRecord['student']) {
            $questionRecord['student']['gradeInfo'] = Grade::where('id', $questionRecord['student']['gradeId'])->find();
        }

        // 获取上课记录信息
        $skRecord = null;
        if ($questionRecord['skRecordId']) {
            $skRecord = LearnSkRecord::where(['id' => $questionRecord['skRecordId']])
                ->field('id,studentClassMinuteTotal,studentClassMinute,trainerEvaluate')
                ->find();

            if (empty($skRecord)) {
                getResponseException('上课记录不存在', [], 1, 'ERROR');
            }
        }

        // 获取句子库年级信息
        $sayGradeInfo = SayTeachSentence::alias('a')
            ->join('banxi_say_grade b', 'b.id = a.gradeId')
            ->where(['a.id' => $questionRecord['sayTeachSentenceId']])
            ->field('b.id,b.name,a.name as sentenceName')
            ->find();
        if ($sayGradeInfo) {
            $sayGradeInfo['name'] = "{$sayGradeInfo['name']}【{$sayGradeInfo['sentenceName']}】({$questionRecord['learnSentenceCount']})";
        }

        // 获取答题详情列表
        $list = LearnSayQuestionAnswerRecord::where([
            ['recordId', "=", $questionRecord['id']],
            ['isCorrect', "=", 0]
        ])
            ->field('id,sentenceEn,sentenceZh,sentenceAudio,sentenceWordColor,isCorrect')
            ->select()
            ->each(function ($item) {
                $item['isCorrect'] = (bool)$item['isCorrect'];
                return $item;
            })
            ->toArray();

        // 获取复习统计数据
        $reviewData = (new LearnSayReviewRecord())->getReviewRecordStatistics($questionRecord['skRecordId']);
        return [
            'sayGradeInfo' => $sayGradeInfo,
            'reviewData' => $reviewData,
            'skRecord' => $skRecord,
            'questionRecord' => $questionRecord,
            'list' => $list
        ];
    }

    //学习报告
    public function questionReportAll($skRecordId)
    {
        // 获取学习记录及关联信息
        $LearnSkRecordModel = new LearnSkRecordModel();
        $skRecord = $LearnSkRecordModel->with([
            'studentInfo' => function ($query) {
                $query->field('id,name,avatar,gradeId');
            },
            'trainerInfo' => function ($query) {
                $query->field('id,name');
            }
        ])->field('id,studentId,trainerId,courseId,trainerEvaluate,studentClassMinuteTotal,studentClassMinute,actualStartTime')
            ->where(['id' => $skRecordId])
            ->find();
        if (empty($skRecord)) {
            getResponseException('上课记录不存在', [], 1, 'ERROR');
        }
        //正课
        $learnSayQuestionRecord = new LearnSayQuestionRecord();
        $studyData = $learnSayQuestionRecord->geQuestionRecordStatistics($skRecordId);
        $sayGradeInfo = ['name' => $studyData['sentenceGradeName']];
        unset($studyData['sentenceGradeName']);
        //课前
        $learnSayReviewRecordModel = new LearnSayReviewRecord();
        $reviewData = $learnSayReviewRecordModel->getReviewRecordStatistics($skRecordId);
        //学生班级
        $skRecord['studentInfo']['gradeInfo'] = null;
        if ($skRecord['studentInfo']) {
            $skRecord['studentInfo']['gradeInfo'] = Grade::where('id', $skRecord['studentInfo']['gradeId'])->find() ?? null;
        }

        $sayTeachSentenceModel = new SayTeachSentence();
        $list = $sayTeachSentenceModel->alias('a')
            ->join('banxi_learn_say_question_answer_record b', 'b.sayTeachSentenceId = a.id')
            ->join('banxi_learn_say_question_record c', 'c.id = b.recordId')
            ->group('b.sayTeachSentenceId')
            ->where([
                ['c.skRecordId', '=', $skRecord['id']],
                ['b.isCorrect', '=', 0],
                ['b.del', '=', 0],
                ['c.del', '=', 0]
            ])->field('b.id,a.sentenceEn,a.sentenceZh,a.sentencePhonetic,a.sentenceAudio,a.sentenceImage,a.sentenceWordColor,a.question,a.answer,b.isCorrect,b.translationCorrect,b.answerCorrect')->select()->toArray();
        foreach ($list as $key => $item) {
            $list[$key]['isCorrect'] = (bool)$item['isCorrect'];
        }
        return [
            'sayGradeInfo' => $sayGradeInfo,
            'studyData' => $studyData,
            'reviewData' => $reviewData,
            'skRecord' => $skRecord,
            'list' => $list
        ];
    }


    //-------------------------------------------------------------------------------------
    //                                   复习                                              -
    //-------------------------------------------------------------------------------------

    /**
     * 开始句型复习
     * @param int|null $skRecordId 上课记录ID
     * @param int|null $studentId 学生ID
     * @param int|null $trainerId 教练ID
     * @param int $learnMeans 学习方式（1-教学，2-练习）
     * @param int $teachSentenceId 句型母句id
     * @return array|int
     * @throws Exception
     */
    public function startSayReview($skRecordId, $trainerId, $studentId, $reviewType)
    {
        if ($skRecordId) {
            $LearnSkRecordModel = new LearnSkRecord();
            $skRecord = $LearnSkRecordModel->where('id', $skRecordId)->find();
            if (empty($skRecord)) {
                $this->setError('上课记录不存在');
                return false;
            }
        }
        $LearnSayQuestionRecordModel = new LearnSayQuestionRecord();

        if ($trainerId) {
            $trainer = Trainer::where('id', $trainerId)->find();
            // 验证学生是否存在
            if (empty($trainer)) {
                $this->setError('教练不存在');
                return false;
            }
        }
        $student = Student::where('id', $studentId)->find();
        // 验证学生是否存在
        if (empty($student)) {
            $this->setError('学员不存在');
            return false;
        }
        $studentOrgId = $student['organizationId'];

        $LearnSayQuestionAnswerRecordModel = new LearnSayQuestionAnswerRecord();
        if ($reviewType == 1) {
            $LearnSkRecordModel = new LearnSkRecord();
            $where = [
                'studentId' => $studentId,
                'isEnd' => 1
            ];
            if ($trainerId) {
                $where['trainerId'] = $trainerId;
            }
            $skRecord = $LearnSkRecordModel->where($where)->order(['actualStartTime' => 'desc'])->column('id');
            if (empty($skRecord)) {
                $this->setError('没有可复习数据');
                return false;
            }
            $sayQuestionRecordIds = $LearnSayQuestionRecordModel->where([
                ['skRecordId', 'in', $skRecord],
                ['isSubmit', '=', 1],
                ['learnMeans', '=', LearnMeansEnum::E1],
            ])->order(['answerStartTime' => 'desc'])
                ->limit(2)
                ->column('id');
            if (empty($sayQuestionRecordIds)) {
                $this->setError('没有可复习数据');
                return false;
            }
            $where = [
                ['recordId', 'in', $sayQuestionRecordIds],
            ];
            $historyTeachSentence = $LearnSayQuestionAnswerRecordModel->where($where)->group('sayTeachSentenceId')->order(['id' => 'asc'])->limit(32)->select()->toArray();
        } else {
            $where = [
                'studentId' => $studentId
            ];
            if ($trainerId) {
                $where['trainerId'] = $trainerId;
            }
            $historyTeachSentence = $LearnSayQuestionAnswerRecordModel->where($where)->orderRaw('RAND()')->group('sayTeachSentenceId')->limit(32)->select()->toArray();
        }
        if (empty($historyTeachSentence)) {
            $this->setError('没有可复习数据');
            return false;
        }
        Db::startTrans();
        try {
            $LearnSayReviewRecordData = [
                'skRecordId' => $skRecordId,
                'trainerId' => $trainerId,
                'studentId' => $studentId,
                'studentOrgId' => $studentOrgId,
                'passRate' => 60,
                'answerStartTime' => date('Y-m-d H:i:s', time())
            ];
            $LearnSayReviewRecordModel = new LearnSayReviewRecord();
            $record = $LearnSayReviewRecordModel->create($LearnSayReviewRecordData);
            foreach ($historyTeachSentence as $it) {
                $updateLearnSayAnswerList[] = [
                    'recordId' => $record->id,
                    'trainerId' => $trainerId,
                    'studentId' => $studentId,
                    'parentTeachSentenceId' => $it['parentTeachSentenceId'],
                    'sayTeachSentenceId' => $it['sayTeachSentenceId'],
                    'sayTeachSentenceName' => $it['sayTeachSentenceName'],
                    'sentenceEn' => $it['sentenceEn'],
                    'sentenceZh' => $it['sentenceZh'],
                    'sentencePhonetic' => $it['sentencePhonetic'],
                    'sentenceAudio' => $it['sentenceAudio'],
                    'sentenceWordColor' => $it['sentenceWordColor'],
                    'sentenceImage' => $it['sentenceImage'],
                    'isCorrect' => ''
                ];
            }
            $LearnSayReviewSentenceRecordModel = new LearnSayReviewSentenceRecord();
            $LearnSayReviewSentenceRecordModel->saveAll($updateLearnSayAnswerList);
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
        return [
            'recordId' => $record->id,
            'reviewList' => $updateLearnSayAnswerList
        ];
    }

    /**
     * 提交句型复习
     * @param int $skRecordId 上课ID
     * @param int|null $trainerId 教练ID
     * @param int|null $studentId 学生ID
     * @param array|null $reviewList 答案列表
     * @throws Exception
     */
    public function answerSayReview($recordId, $trainerId, $studentId, $reviewList)
    {
        Db::startTrans();
        try {
            $LearnSkRecordModel = new LearnSkRecord();
            $LearnSayReviewRecordModel = new LearnSayReviewRecord();
            // 查询上课记录
            $LearnSayReviewRecord = $LearnSayReviewRecordModel->where('id', $recordId)->find();
            // 验证上课记录是否存在
            if (empty($LearnSayReviewRecord)) {
                throw new ValidateException('复习记录不存在');
            }
            if ($LearnSayReviewRecord['isSubmit'] == 1) {
                throw new ValidateException('请勿重复提交');
            }

            // 验证教练权限
            if ($LearnSayReviewRecord['trainerId'] != $trainerId) {
                throw new ValidateException('复习记录不存在');
            }


            // 验证学生权限
            if ($LearnSayReviewRecord['studentId'] != $studentId) {
                throw new ValidateException('复习记录不存在');
            }


            $skRecordId = $LearnSayReviewRecord['skRecordId'];
            $strangeType = StrangeTypeEnum::E2;
            if ($skRecordId) {
                // 查询上课记录
                $learnSkRecord = $LearnSkRecordModel->where('id', $skRecordId)->find();
                // 验证上课记录是否存在
                if (empty($learnSkRecord)) {
                    throw new ValidateException('复习记录不存在');
                }
                $strangeType = StrangeTypeEnum::E1;
            }
            $learnSayReviewSentenceRecordModel = new LearnSayReviewSentenceRecord();
            $learnSayReviewSentenceRecordList = $learnSayReviewSentenceRecordModel
                ->where('recordId', $recordId)
                ->select();
            if (empty($learnSayReviewSentenceRecordList)) {
                throw new ValidateException('提交失败，当前复习记录无数据');
            }
            $studentSaySentence = [];
            $updateLearnSayReviewList = [];
            foreach ($learnSayReviewSentenceRecordList as $it) {
                $result = null;
                // 在用户答案中查找对应题目的答案
                if (!empty($reviewList)) {
                    foreach ($reviewList as $review) {
                        if (isset($review['sayTeachSentenceId']) && $review['sayTeachSentenceId'] == $it['sayTeachSentenceId']) {
                            $result = $review;
                            break;
                        }
                    }
                }

                // 判断题目是否正确
                $isCorrect = false;
                $answerRecordId = 0;
                if ($result !== null) {
                    //获取答题记录ID
                    $reviewRecord = $learnSayReviewSentenceRecordModel->where(['sayTeachSentenceId' => $result['sayTeachSentenceId'], 'recordId' => $recordId])->find();
                    $answerRecordId = $reviewRecord['id'];
                    $isCorrect = $result['isCorrect'];
                    //生词本
                    $studentSaySentence[] = [
                        'studentId' => $studentId,
                        'sayTeachSentenceId' => $it['sayTeachSentenceId'],
                        'strangeType' => $strangeType,
                        'sentenceEn' => $it['sentenceEn'],
                        'sentenceZh' => $it['sentenceZh'],
                        'sentencePhonetic' => $it['sentencePhonetic'],
                        'sentenceAudio' => $it['sentenceAudio'],
                        'sentenceImage' => $it['sentenceImage'],
                        'sentenceWordColor' => $it['sentenceWordColor'],
                        'isCorrect' => $isCorrect
                    ];
                }

                // 构造更新数据
                $updateLearnSayReviewList[] = [
                    'answerRecordId' => $answerRecordId,
                    'isCorrect' => $isCorrect,
                ];
            }
            $totalNum = count($updateLearnSayReviewList);
            $correctNum = 0;

            foreach ($updateLearnSayReviewList as $answer) {
                if ($answer['isCorrect']) {
                    $correctNum++;
                }
            }

            $errorNum = $totalNum - $correctNum;
            $correctRate = $totalNum > 0 ? intval($correctNum * 100 / $totalNum) : 0;

            // 构造更新数据
            $endTimeStamp = time();
            $useTime = $endTimeStamp - strtotime($LearnSayReviewRecord['answerStartTime']);
            $updateLearnSayReviewRecordData = [
                'totalNum' => $totalNum,
                'rightNum' => $correctNum,
                'errorNum' => $errorNum,
                'rightRate' => $correctRate,
                'answerEndTime' => date('Y-m-d H:i:s', $endTimeStamp),
                'useTime' => $useTime,
                'isSubmit' => 1,
                'updateTime' => time()
            ];

            $LearnSayReviewRecordModel
                ->update($updateLearnSayReviewRecordData, ['id' => $recordId]);
            // 更新答题答案
            foreach ($updateLearnSayReviewList as $answer) {
                $learnSayReviewSentenceRecordModel
                    ->update([
                        'isCorrect' => $answer['isCorrect'],
                        'updateTime' => time()
                    ], ['id' => $answer['answerRecordId']]);
            }
            //生词本
            $StudentSaySentenceModel = new StudentSaySentence();
            $StudentSaySentenceModel->saveStudentSentence($studentSaySentence);
            Db::commit();
            return $recordId;
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }

    }

    //-------------------------------------------------------------------------------------
    //                                   抗遗忘                                              -
    //-------------------------------------------------------------------------------------

    public function startSayForgetting($forgettingId, $accountId, $accountType)
    {
        $where = ['id' => $forgettingId];
        switch ($accountType) {
            case AccountTypeEnum::TRAINER:
                $where['trainerAntiForgettingId'] = $accountId;
                break;
            case AccountTypeEnum::STUDENT:
                $where['studentId'] = $accountId;
                break;
            default:
                getResponseException('不支持的账户类型', [], 1, 'ERROR');
        }
        $LearnSayAntiForgettingModel = new LearnSayAntiForgettingModel();
        $forgettingRecord = $LearnSayAntiForgettingModel
            ->where($where)
            ->find();
        if (!$forgettingRecord) {
            getResponseException('抗遗忘记录不存在', [], 1, 'ERROR');
        }
        if ($forgettingRecord['status'] != LearnSayAntiForgettingStatusEnum::E1) {
            getResponseException('请勿重复提交', [], 1, 'ERROR');
        }
        // if ($forgettingRecord['date'] != date('Y-m-d')) {
        //     getResponseException('未到抗遗忘时间', [], 1, 'ERROR');
        // }
        // $LearnSayAntiForgettingReviewModel = new LearnSayAntiForgettingReview();
        // $reviewRecordInfo = $LearnSayAntiForgettingReviewModel->where([
        //     'antiForgettingId' => $forgettingId,
        //     'groupId' => $forgettingRecord['groupId'],
        //     'isSubmit' => 0
        // ])->value('id');
        // if ($reviewRecordInfo) {
        //     $reviewRecordInfo->answerStartTime = date('Y-m-d H:i:s');
        //     $reviewRecordInfo->save();
        //     return $reviewRecordInfo['id'];
        // }
        Db::startTrans();
        try {
            $forgettingRecord->status = LearnSayAntiForgettingStatusEnum::E2;
            $forgettingRecord->answerStartTime = date('Y-m-d H:i:s');
            $forgettingRecord->save();
            $LearnSayAntiForgettingSentenceModel = new LearnSayAntiForgettingSentence();
            $forgettingSentenceList = $LearnSayAntiForgettingSentenceModel->where([
                'questionRecordId' => $forgettingRecord['questionRecordId'],
                'groupId' => $forgettingRecord['groupId']
            ])->select()->toArray();
            if (empty($forgettingSentenceList)) {
                throw new ValidateException('没有可抗遗忘数据');
            }
            $forgettingReviewSentenceData = [];
            foreach ($forgettingSentenceList as $item) {
                $forgettingReviewSentenceData[] = [
                    'forgettingId' => $forgettingId,
                    'studentId' => $forgettingRecord['studentId'],
                    'trainerId' => $forgettingRecord['trainerAntiForgettingId'],
                    'parentTeachSentenceId' => $item['parentTeachSentenceId'],
                    'sayTeachSentenceId' => $item['sayTeachSentenceId'],
                    'sayTeachSentenceName' => $item['sayTeachSentenceName'],
                    'sentenceEn' => $item['sentenceEn'],
                    'sentenceZh' => $item['sentenceZh'],
                    'sentencePhonetic' => $item['sentencePhonetic'],
                    'sentenceAudio' => $item['sentenceAudio'],
                    'sentenceImage' => $item['sentenceImage'],
                    'sentenceWordColor' => $item['sentenceWordColor'],
                    'isCorrect' => '',
                    'listenCorrect' => '',
                    'translationCorrect' => '',
                    'answerCorrectCorrect' => ''
                ];
            }
            $LearnSayAntiForgettingReviewSentenceModel = new LearnSayAntiForgettingAnswer();
            $LearnSayAntiForgettingReviewSentenceModel->saveAll($forgettingReviewSentenceData);
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            getResponseException($e->getMessage(), [], 1, 'ERROR');
        }
        return $forgettingId;
    }

    public function answerSayForgetting($forgettingId, $accountId, $accountType, $reviewList)
    {
        $where = ['id' => $forgettingId];
        switch ($accountType) {
            case AccountTypeEnum::TRAINER:
                $where['trainerAntiForgettingId'] = $accountId;
                break;
            case AccountTypeEnum::STUDENT:
                $where['studentId'] = $accountId;
                break;
            default:
                getResponseException('不支持的账户类型', [], 1, 'ERROR');
        }
        $LearnSayAntiForgettingModel = new LearnSayAntiForgettingModel();
        $forgettingRecord = $LearnSayAntiForgettingModel
            ->where($where)
            ->find();
        if (!$forgettingRecord) {
            getResponseException('抗遗忘记录不存在', [], 1, 'ERROR');
        }
        if ($forgettingRecord['status'] == LearnSayAntiForgettingStatusEnum::E1) {
            getResponseException('抗遗忘未开始', [], 1, 'ERROR');
        }
        if ($forgettingRecord['status'] == LearnSayAntiForgettingStatusEnum::E3) {
            getResponseException('抗遗忘已结束', [], 1, 'ERROR');
        }
        Db::startTrans();
        try {
            //查询抗遗忘数据
            $LearnSayAntiForgettingAnswerModel = new LearnSayAntiForgettingAnswer();
            $learnSayAntiForgettingReviewSentenceList = $LearnSayAntiForgettingAnswerModel
                ->where([
                    'forgettingId' => $forgettingId
                ])
                ->select();
            if (empty($learnSayAntiForgettingReviewSentenceList)) {
                throw new ValidateException('提交失败，当前抗遗忘记录无数据');
            }
            $studentSaySentence = [];
            $updateLearnSayForgettingReviewList = [];

            $learnNum = 0;//听力
            $translationLearnNum = 0;//汉译英
            $questionLearnNum = 0;//考点复现
            foreach ($learnSayAntiForgettingReviewSentenceList as $it) {
                $result = null;
                // 在用户答案中查找对应题目的答案
                if (!empty($reviewList)) {
                    foreach ($reviewList as $review) {
                        if (isset($review['id']) && $review['id'] == $it['id']) {
                            $result = $review;
                            break;
                        }
                    }
                }

                // 判断题目是否正确
                if ($result !== null) {
                    //获取答题记录ID
                    $reviewRecord = $LearnSayAntiForgettingAnswerModel->where(['id' => $result['id'], 'forgettingId' => $forgettingId])->find();
                    $answerRecordId = $reviewRecord['id'];
                    $listenCorrect = (int)$result['listenCorrect'];
                    $translationCorrect = (int)$result['translationCorrect'];
                    $questionCorrect = (int)$result['questionCorrect'];
                    $learnNum++;
                    $translationLearnNum++;
                    $questionLearnNum++;
                    $isCorrect = (int)($listenCorrect && $translationCorrect && $questionCorrect);


                    //生词本
                    if ($reviewRecord['studentId']) {
                        $studentSaySentence[] = [
                            'studentId' => $reviewRecord['studentId'],
                            'sayTeachSentenceId' => $it['sayTeachSentenceId'],
                            'strangeType' => StrangeTypeEnum::E1,
                            'sentenceEn' => $it['sentenceEn'],
                            'sentenceZh' => $it['sentenceZh'],
                            'sentencePhonetic' => $it['sentencePhonetic'],
                            'sentenceAudio' => $it['sentenceAudio'],
                            'sentenceImage' => $it['sentenceImage'],
                            'sentenceWordColor' => $it['sentenceWordColor'],
                            'isCorrect' => $isCorrect
                        ];
                    }
                    // 构造更新数据
                    $updateLearnSayForgettingReviewList[] = [
                        'answerRecordId' => $answerRecordId,
                        'isCorrect' => $isCorrect,
                        'listenCorrect' => $listenCorrect,
                        'translationCorrect' => $translationCorrect,
                        'questionCorrect' => $questionCorrect,
                    ];
                }

            }
            $totalNum = count($updateLearnSayForgettingReviewList);
            $correctNum = 0;
            $translationCorrectNum = 0;
            $questionCorrectNum = 0;

            foreach ($updateLearnSayForgettingReviewList as $answer) {
                if ($answer['listenCorrect']) {
                    $correctNum++;
                }
                if ($answer['translationCorrect']) {
                    $translationCorrectNum++;
                }
                if ($answer['questionCorrect']) {
                    $questionCorrectNum++;
                }
            }
            //听力
            $errorNum = $learnNum - $correctNum;
            $correctRate = $learnNum > 0 ? intval($correctNum * 100 / $learnNum) : 0;
            //汉译英
            $translationErrorNum = $translationLearnNum - $translationCorrectNum;
            $translationCorrectRate = $translationLearnNum > 0 ? intval($translationCorrectNum * 100 / $translationLearnNum) : 0;
            //考点复现
            $questionErrorNum = $questionLearnNum - $questionCorrectNum;
            $questionCorrectRate = $questionLearnNum > 0 ? intval($questionCorrectNum * 100 / $questionLearnNum) : 0;

            // 构造更新数据
            $endTimeStamp = time();
            $useTime = $endTimeStamp - strtotime($forgettingRecord['answerStartTime']);
            $LearnSayAntiForgettingReviewData = [
                'totalNum' => $totalNum,
                //听力
                'learnNum' => $learnNum,
                'rightNum' => $correctNum,
                'errorNum' => $errorNum,
                'rightRate' => $correctRate,
                //汉译英
                'translationLearnNum' => $translationLearnNum,
                'translationRightNum' => $translationCorrectNum,
                'translationErrorNum' => $translationErrorNum,
                'translationRightRate' => $translationCorrectRate,
                //考点复现
                'questionLearnNum' => $questionLearnNum,
                'questionRightNum' => $questionCorrectNum,
                'questionErrorNum' => $questionErrorNum,
                'questionRightRate' => $questionCorrectRate,
                'answerEndTime' => date('Y-m-d H:i:s', $endTimeStamp),
                'useTime' => $useTime,
                'status' => LearnSayAntiForgettingStatusEnum::E3,
                'updateTime' => time()
            ];

            $LearnSayAntiForgettingModel
                ->update($LearnSayAntiForgettingReviewData, ['id' => $forgettingId]);
            // 更新答题答案
            foreach ($updateLearnSayForgettingReviewList as $answer) {
                $LearnSayAntiForgettingAnswerModel
                    ->update([
                        'isCorrect' => $answer['isCorrect'],
                        'listenCorrect' => $answer['listenCorrect'],
                        'translationCorrect' => $answer['translationCorrect'],
                        'questionCorrect' => $answer['questionCorrect'],
                        'updateTime' => time()
                    ], ['id' => $answer['answerRecordId']]);
            }
            //生词本
            $StudentSaySentenceModel = new StudentSaySentence();
            $StudentSaySentenceModel->saveStudentSentence($studentSaySentence);
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            getResponseException($e->getMessage(), [], 1, 'ERROR');
        }
        return true;
    }
}
